<template>
  <Modal
    v-model:visible="visible"
    :title="getTitle"
    @ok="handleSubmit"
    @cancel="closeModal"
    @close="resetFields()"
    :destroyOnClose="true"
    :maskClosable="true"
    :closable="true"
    okText="确认"
    cancelText="取消"
  >
    <BasicForm @register="registerForm">
      <template #edit>
        <Button @click="editSecret()" type="primary">修改</Button>
      </template>
    </BasicForm>
  </Modal>
</template>

<script lang="ts" setup>
/* eslint-disable */
import { Modal, Button } from 'ant-design-vue';
import { nextTick, ref } from 'vue';
import { useBasicForm } from '/@/components/BasicForm/hooks/useBasicForm';
import BasicForm from '/@/components/BasicForm/BasicForm.vue';
import { moduleSchemas } from '/@/views/system-mgmt/app-mgmt/modal/moduleFormSchema';
import { appSchemas } from '/@/views/system-mgmt/app-mgmt/modal/appFormSchema';
import { authSchemas } from '/@/views/system-mgmt/app-mgmt/modal/authFormSchema';
import { componentSchemas } from '/@/views/system-mgmt/app-mgmt/modal/componentFormSchema';
import { integrateSchemas } from '/@/views/system-mgmt/app-mgmt/modal/integrateFormSchema';
import { syncSchemas } from '/@/views/system-mgmt/app-mgmt/modal/syncFormSchema';

import {
  createOrUpdateCloudLink,
  createOrUpdateModule,
  createOrUpdateProgram,
  getCertifiedIntegration,
  getSyncIntegration,
  updateCertifiedIntegration,
  updateSyncIntegration,
} from '/@/api/system-mgmt/app-mgmt/app';
import {
  addOrUpdateComponent,
  addOrUpdateComponentRelationship,
  getComponentList,
  getComponentListWithoutCurrentComponent,
} from '/@/api/system-mgmt/app-mgmt/component';
import { mirrorSchemas } from '/@/views/system-mgmt/app-mgmt/modal/mirrorFormSchema';
import { createImageMetaInfo, updateImage } from '/@/api/system-mgmt/app-mgmt/image';
import { useMessage } from '/@/hooks/web/useMessage';
import { componentRelationSchemas } from '/@/views/system-mgmt/app-mgmt/modal/componentRelationSchema';

const mirror = ref(undefined);
const getTitle = ref('新增应用程序');
const visible = ref(false);
const types = ref();
const emit = defineEmits(['success']);
const appId = ref();
const ids = ref();
const edit = ref(false);
const { createMessage } = useMessage();
const [registerForm, { updateSchema, setFieldsValue, resetSchema, validate, resetFields }] = useBasicForm({
  labelWidth: 100,
  showActionButtonGroup: false,
});

const openModal = (type: string, id: string, record?: any, mirrorCount?: number) => {
  visible.value = true;
  types.value = type;
  mirror.value = mirrorCount;
  nextTick(() => {
    appId.value = id;
  });
  edit.value = false;
  switch (type) {
    case 'app':
      nextTick(() => {
        getTitle.value = '新增应用程序';
        resetSchema(appSchemas);
        resetFields();
      });
      break;
    case 'auth':
      nextTick(async () => {
        getTitle.value = '认证集成';
        await resetSchema(authSchemas);
        await setFieldsValue(await getCertifiedIntegration({ id: appId.value }));
      });
      break;
    case 'component':
      nextTick(() => {
        getTitle.value = '新增组件';
        resetSchema(componentSchemas);
      });
      break;
    case 'integrate':
      nextTick(() => {
        getTitle.value = '新增第三方应用集成配置';
        resetSchema(integrateSchemas);
        updateSchema([
          {
            field: 'app',
            required: false,
            dynamicDisabled: true,
          },
          {
            field: 'clusterkey',
            required: true,
            dynamicDisabled: false,
          },
          {
            field: 'managePort',
            required: true,
            dynamicDisabled: false,
          },
          {
            field: 'rdpPort',
            required: true,
            dynamicDisabled: false,
          },
        ]);
        setFieldsValue({
          app: '云联',
        });
      });
      resetFields();
      break;
    case 'module':
      nextTick(() => {
        getTitle.value = '新增模块';
        resetSchema(moduleSchemas);
      });
      updateSchema([
        {
          field: 'protocol',
          required: true,
          dynamicDisabled: false,
        },
      ]);
      resetFields();
      break;
    case 'sync':
      nextTick(async () => {
        getTitle.value = '同步集成';
        await resetSchema(syncSchemas);
        await setFieldsValue(await getSyncIntegration({ id: appId.value }));
        await updateSchema({
          field: 'cmRsaPrivateKey',
          dynamicDisabled: true,
          componentProps: {
            placeHolder: '请输入RSA私钥',
            visibilityToggle: false,
          },
        });
      });
      break;
    case 'mirror':
      nextTick(async () => {
        getTitle.value = '组件镜像';
        await resetSchema(mirrorSchemas);
        await setFieldsValue({ appId: appId.value, preferred: false });
        await updateSchema([
          {
            field: 'name',
            required: true,
            dynamicDisabled: false,
          },
          {
            field: 'preferred',
            required: true,
            dynamicDisabled: false,
          },
        ]);
      });
      break;

    case 'componentRelationship':
      nextTick(async () => {
        getTitle.value = '新增组件关系';
        await resetSchema(componentRelationSchemas);
        await updateSchema([
          {
            field: 'upstreamComponentId',
            required: false,
            dynamicDisabled: true,
          },
          {
            field: 'downstreamComponentId',
            required: false,
            dynamicDisabled: true,
          },
        ]);
        await updateSchema([
          {
            field: 'componentId',
            label: '组件名称',
            component: 'ApiSelect',
            dynamicDisabled: false,
            componentProps: (formActionType) => {
              return {
                placeHolder: '请选择组件',
                api: getComponentList,
                params: {
                  appId: appId.value,
                },
                resultField: 'list',
                labelField: 'name',
                valueField: 'id',
                onChange: async (e) => {
                  setFieldsValue({ upstreamComponentId: undefined, downstreamComponentId: undefined });
                  updateSchema([
                    {
                      field: 'upstreamComponentId',
                      dynamicDisabled: false,
                      componentProps: {
                        placeHolder: '请选择上游组件',
                        api: getComponentListWithoutCurrentComponent,
                        params: {
                          appId: appId.value,
                          current: e,
                        },
                        resultField: 'list',
                        labelField: 'name',
                        valueField: 'id',
                      },
                    },
                    {
                      field: 'downstreamComponentId',
                      dynamicDisabled: false,
                      componentProps: {
                        placeHolder: '请选择下游组件',
                        api: getComponentListWithoutCurrentComponent,
                        params: {
                          appId: appId.value,
                          current: e,
                        },
                        resultField: 'list',
                        labelField: 'name',
                        valueField: 'id',
                      },
                    },
                  ]);
                },
              };
            },
            labelWidth: 100,
            colProps: { span: 24 },
            required: true,
          },
        ]);
      });
      break;
  }
  if (record !== undefined) {
    switch (type) {
      case 'app':
        edit.value = true;
        ids.value = record.id;
        nextTick(() => {
          getTitle.value = '编辑应用程序';
          updateSchema([
            {
              field: 'programName',
              required: false,
              dynamicDisabled: true,
            },
            {
              field: 'programVersion',
              required: false,
              dynamicDisabled: true,
            },
          ]);
          setFieldsValue(record);
        });
        break;
      case 'integrate':
        edit.value = true;
        ids.value = record.id;
        nextTick(() => {
          getTitle.value = '编辑第三方应用集成配置';
          updateSchema([
            {
              field: 'app',
              required: false,
              dynamicDisabled: true,
            },
            {
              field: 'clusterkey',
              required: false,
              dynamicDisabled: true,
            },
            {
              field: 'managePort',
              required: false,
              dynamicDisabled: true,
            },
            {
              field: 'rdpPort',
              required: false,
              dynamicDisabled: true,
            },
          ]);
          setFieldsValue({
            app: '云联',
          });
          setFieldsValue(record);
          updateSchema({
            field: 'clusterkey',
            dynamicDisabled: true,
            componentProps: {
              placeHolder: '请输入云联clusterKey',
              visibilityToggle: false,
            },
          });
        });

        break;
      case 'module':
        edit.value = true;
        ids.value = record.id;
        nextTick(() => {
          getTitle.value = '编辑模块';
          updateSchema([
            {
              field: 'protocol',
              required: false,
              dynamicDisabled: true,
            },
          ]);
          setFieldsValue(record);
        });
        break;
      case 'component':
        edit.value = true;
        ids.value = record.id;
        nextTick(async () => {
          await resetSchema(componentSchemas);
          getTitle.value = '编辑组件';
          setFieldsValue(record);
        });
        break;
      case 'mirror':
        edit.value = true;
        ids.value = record.id;

        nextTick(async () => {
          await resetSchema(mirrorSchemas);
          getTitle.value = '编辑组件镜像';
          await setFieldsValue(record);
          await updateSchema([
            {
              field: 'componentId',
              required: false,
              dynamicDisabled: true,
            },
            {
              field: 'preferred',
              required: false,
              dynamicDisabled: () => {
                if (record.preferred == true) {
                  return true;
                } else {
                  return false;
                }
              },
            },
          ]);
        });
        break;
      case 'componentRelationship':
        edit.value = true;
        ids.value = record.id;

        nextTick(async () => {
          await resetSchema(componentRelationSchemas);
          getTitle.value = '编辑组件关系';
          await setFieldsValue({
            componentId: record.componentId,
            upstreamComponentId: record.upstreamComponentId,
            downstreamComponentId: record.downstreamComponentId,
          });
          await updateSchema([
            {
              field: 'componentId',
              required: false,
              dynamicDisabled: true,
            },
            {
              field: 'upstreamComponentId',
              required: false,
              dynamicDisabled: false,
              componentProps: {
                api: getComponentListWithoutCurrentComponent,
                params: {
                  appId: appId.value,
                  current: record.componentId,
                },
                mode: 'multiple',
                resultField: 'list',
                labelField: 'name',
                valueField: 'id',
              },
            },
            {
              field: 'downstreamComponentId',
              required: false,
              dynamicDisabled: false,
              componentProps: {
                api: getComponentListWithoutCurrentComponent,
                params: {
                  appId: appId.value,
                  current: record.componentId,
                },
                mode: 'multiple',
                resultField: 'list',
                labelField: 'name',
                valueField: 'id',
              },
            },
          ]);
        });
        break;
    }
  }
};
const closeModal = async () => {
  await resetFields();
  visible.value = false;
};

const handleSubmit = async () => {
  const params = await validate();
  if (edit.value === true) {
    params.id = ids.value;
  }
  let res;
  switch (types.value) {
    case 'app':
      params.appId = appId.value;
      res = await createOrUpdateProgram(params);
      break;
    case 'auth':
      params.id = appId.value;
      res = await updateCertifiedIntegration(params);
      break;
    case 'component':
      params.appId = appId.value;
      res = await addOrUpdateComponent(params);
      break;
    case 'integrate':
      params.appId = appId.value;
      res = await createOrUpdateCloudLink(params);
      break;
    case 'module':
      params.appId = appId.value;
      res = await createOrUpdateModule(params);
      break;
    case 'sync':
      params.id = appId.value;
      res = await updateSyncIntegration(params);
      break;
    case 'mirror':
      params.appId = appId.value;
      if (edit.value === true) {
        res = await updateImage(params);
      } else {
        res = await createImageMetaInfo(params);
      }
      break;
    case 'componentRelationship':
      params.appId = appId.value;
      res = await addOrUpdateComponentRelationship(params);
      break;
  }

  if (res === 1 || res.includes('成功') || res.includes('完成')) {
    createMessage.success('操作成功');
  } else {
    createMessage.error('操作失败');
  }

  emit('success');
  closeModal();
};

const editSecret = () => {
  switch (types.value) {
    case 'sync':
      updateSchema({
        field: 'cmRsaPrivateKey',
        dynamicDisabled: false,
        componentProps: {
          placeHolder: '请输入RSA私钥',
          visibilityToggle: true,
        },
      });
      break;
    case 'integrate':
      updateSchema({
        field: 'clusterkey',
        dynamicDisabled: false,
        componentProps: {
          placeHolder: '请输入云联clusterKey',
          visibilityToggle: true,
        },
      });
      break;
  }
};

defineExpose({ openModal });
</script>
